package com.yonyou.wdt.job;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.yonyou.wdt.dao.JobLogDao;
import com.yonyou.wdt.entity.OpenApiURLEnum;
import com.yonyou.wdt.entity.QueryDto;
import com.yonyou.wdt.job.config.BaseConfig;
import com.yonyou.wdt.model.JobLogModel;
import com.yonyou.wdt.service.YonsuiteService;
import com.yonyou.wdt.utils.DateUtils;
import com.yonyou.wdt.utils.RedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

@Component
public class YsCustToRedisJob extends BaseConfig {
    private static Logger logger = LoggerFactory.getLogger(YsProductToRedisJob.class);
    @Resource
    private YonsuiteService yonsuiteService;
    @Resource
    public JobLogDao jobLogDao;

    @XxlJob("ysCustToRedisJob")
    public ReturnT<String> ysCustToRedisJob() {
        String param = XxlJobHelper.getJobParam();
        HashMap<String, Object> queryMap = new HashMap<>();  // 客户档案列表查询请求参数Map
        if (param != null && !"".equals(param)) {
            List<String> timeRange = Arrays.asList(param.split("\\|"));
            if (timeRange.size() == 2) {
                queryMap.put("beganTime", timeRange.get(0));
                queryMap.put("endTime", timeRange.get(1));
            } else {
                queryMap.put("code", timeRange.get(0));
            }
        } else {
            // 默认查询前一天的数据
            queryMap.put("beganTime", DateUtils.getStartDate());
            queryMap.put("endTime", DateUtils.getEndDate());
        }
        // 处理相关业务
        QueryDto dto = new QueryDto();
        dto.setTenantId(getYsTenantId());
        dto.setAppKey(getYsAppKey());
        dto.setAppSecret(getYsAppSecret());
        // 获取YS系统租户动态域名信息
        ReturnT<String> isReturn2 = getYsDynamicDomainName(dto);
        // 域名获取失败
        if (isReturn2 != null) return isReturn2;
        try {
            // 1、客户列表查询，查询出所有客户，将id与code拼装成一个map集合，进行比对判断

            ArrayList<JSONObject> custList = new ArrayList<>();  // 2B客户档案列表查询返回值
            int pageIndex = 1;
            while (true) {
                queryMap.put("pageIndex", pageIndex);
                queryMap.put("pageSize", 500);
                JSONObject wareJsonList = yonsuiteService.merchantListQuery(queryMap, dto);
                if (wareJsonList.getStr("code").equals("200")) {
                    if (null != wareJsonList.getJSONArray("data")) {
                        JSONArray custJSONArray = wareJsonList.getJSONArray("data");
                        for (Object custObj : custJSONArray) {
                            JSONObject entries = JSONUtil.parseObj(custObj);
                            HashMap<String, Object> dtlQueryMap = new HashMap<>();
                            ArrayList<Object> objects = new ArrayList<>();
                            dtlQueryMap.put("code", entries.getStr("code"));
                            objects.add(dtlQueryMap);
                            JSONObject dtlEntries = yonsuiteService.merchantDtlQuery(objects, dto);
                            if (dtlEntries.getStr("code").equals("200")) {
                                if (null != dtlEntries.getJSONArray("data")) {
                                    JSONArray dtlJSONArray = dtlEntries.getJSONArray("data");
                                    JSONObject dataJson = JSONUtil.parseObj(dtlJSONArray.get(0));
                                    JSONObject jsonObject = dataJson.getJSONObject("merchantAppliedDetail");
                                    if (jsonObject != null && StringUtils.isNotBlank(jsonObject.getStr("customerLevelId"))) {
                                        entries.set("customerLevelId", jsonObject.getStr("customerLevelId"));
                                    }
                                }
                            }
                            this.APICurrentLimiting(OpenApiURLEnum.MERCHANT_DTL_QUERY, 59);
                            custList.add(entries);
                        }
                    }
                } else {
                    break;
                }
                pageIndex++;
                this.APICurrentLimiting(OpenApiURLEnum.MERCHANT_LIST_QUERY, 59);
            }
            logger.info("YS系统客户档案查询完成共：{}个客户", custList.size());
            if (!custList.isEmpty()) {
                for (JSONObject entries : custList) {
                    RedisUtils.set(dto.getTenantId() + ":cust:" + entries.getStr("code"), entries);
                }
            }
            InsertLogger(null, "1", "YS系统客户档案查询完成共，共：{" + custList.size() + "}条");

        } catch (Exception e) {
            XxlJobHelper.handleFail(e.getMessage());
            InsertLogger(null, "0", e.getMessage());
            return ReturnT.FAIL;
        }
        return ReturnT.SUCCESS;
    }

    /**
     * @Author Huangwb
     * @Description 查询YS系统租户动态域名信息
     * @Date 2023/10/30 15:45
     **/
    public ReturnT<String> getYsDynamicDomainName(QueryDto ysQueryDto) {
        try {
            String tenantId = ysQueryDto.getTenantId();  // 租户ID
            if (RedisUtils.get(tenantId + ":DynamicDomainName") == null) {
                // 根据租户ID查询动态域名
                JSONObject dynamicDomainName = yonsuiteService.getDynamicDomainName(null, tenantId);
                if (null != dynamicDomainName && !dynamicDomainName.isEmpty()) {
                    // 将动态域名存入Redis
                    RedisUtils.set(tenantId + ":DynamicDomainName", dynamicDomainName, 86400 * 30);
                } else {
                    logger.error("查询租户【{}】动态域名失败，请重试", tenantId);
                    // insertXxlJobLog(null, "0", "租户：【" + tenantId + "】获取动态域名失败，请稍后重试", jobClassType);
                    InsertLogger(null, "0", "获取动态域名失败");
                    return new ReturnT<>(ReturnT.FAIL_CODE, "查询租户【" + tenantId + "】动态域名失败，请重试");
                }
            }
            // 获取Redis中指定租户动态域名
            JSONObject dynamicDomainNameRedis = (JSONObject) RedisUtils.get(tenantId + ":DynamicDomainName");
            ysQueryDto.setGatewayUrl(dynamicDomainNameRedis.getStr("gatewayUrl"));
            ysQueryDto.setTokenUrl(dynamicDomainNameRedis.getStr("tokenUrl"));
            return null;
        } catch (Exception e) {
            return new ReturnT<>(ReturnT.FAIL_CODE, "获取动态域名失败：" + e.getMessage());
        }
    }

    /**
     * @return
     * @Author Huangwb
     * @Description 插入数据库日志信息
     * @Date 10:30 2023/9/14
     * @Param
     **/
    private void InsertLogger(String code, String oneL, String mags) {  // 单据编号、是否成功、详细信息
        try {
            JobLogModel jobLogDTO = new JobLogModel();
            jobLogDTO.setJobClass("HYZM011");
            jobLogDTO.setJobCode(code);
            jobLogDTO.setJobTime(new Date());
            jobLogDTO.setJobResult(oneL);
            jobLogDTO.setJobResultMessage(mags);
            jobLogDTO.setJobLogUser("dxroot");
            jobLogDao.insertJobLog(jobLogDTO);
        } catch (Exception e) {
            logger.error("插入日志错误：" + e.getMessage());
        }
    }

}
